<?php

namespace App\Repositories;

use App\Enums\MallEnum;
use App\Exceptions\BasicException;
use App\Response\Response;
use Illuminate\Support\Facades\DB;
use App\Services\Tools\ObsService;

//靓号
class GoodCodeRepository
{
    //新增或编辑靓号分类
    public function addOrEditCate($param)
    {
        $id = $param['cate_id'] ?? 0;
        $parentCateId = $param['parent_cate_id'];
        $goodCodeName = $param['good_code_name'];

        if ($parentCateId == 0) {
            $parentId = MallEnum::PRODUCT_CATE_ID_GOOD_CODE;
        } else {
            if ($parentCateId == MallEnum::PRODUCT_CATE_ID_OVERLAP_CODE) {
                throw new BasicException(0, '叠字号不能有子分类');
            }
            $cateIds = app('model_mall_categories')
                ->select('id')
                ->where('parent_id', MallEnum::PRODUCT_CATE_ID_GOOD_CODE)
                ->pluck('id')->toArray();
            if (!in_array($parentCateId, $cateIds)) {
                throw new BasicException(0, '父分类id错误');
            }
            $parentId = $parentCateId;
        }

        $data = [
            'parent_id' => $parentId,
            'title' => $goodCodeName,
        ];
        if ($id > 0) {
            $action = '编辑';
            $res = app('model_mall_categories')->where('id', $id)->update($data);
        } else {
            $action = '添加';
            //查询父分类下已有的子分类数量，超过3个不允许再添加
            $subCateCount = app('model_mall_categories')->where('parent_id', $parentId)->where('is_show', 1)->count();
            if ($subCateCount >= 3) throw new BasicException(0, '子分类数量已有3个，无法继续添加');
            $data['add_time'] = time();
            $res = app('model_mall_categories')->insert($data);
        }

        if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(0, "{$action}失败");
        }
    }

    //新增或编辑靓号
    public function addOrEdit($param)
    {
        $id = $param['id'] ?? 0;
        $goodCode = $param['good_code'];
        $cate1Id = $param['cate1_id'];
        $cate2Id = $param['cate2_id'] ?? $cate1Id;
        $saleStatus = $param['sale_status'];
        $daysPrices = $param['days_price'];

        $exist = app('model_mall_products')->where('title', $goodCode)->where('id', '<>', $id)->first();
        if ($exist) throw new BasicException(0, '靓号已经存在');

        $cateIds = app('model_mall_categories')->getAllSubCateId(MallEnum::PRODUCT_CATE_ID_GOOD_CODE);
        if (!in_array($cate1Id, $cateIds)) throw new BasicException(0, '父分类id错误');

        //叠字号无2级分类，其它类型必须有二级分类
        if ($cate1Id == MallEnum::PRODUCT_CATE_ID_OVERLAP_CODE) {
            $cateId = MallEnum::PRODUCT_CATE_ID_OVERLAP_CODE;
        } else {
            //查询二级分类
            $cate2Ids = app('model_mall_categories')->where('parent_id', $cate1Id)->pluck('id')->toArray();
            if (empty($cate2Ids)) {
                throw new BasicException(0, '请先添加二级分类');
            }
            if (empty($cate2Id)) {
                throw new BasicException(0, '请选择二级分类');
            }
            if (!in_array($cate2Id, $cate2Ids)) throw new BasicException(0, '二级分类id与一级分类id不匹配');
            $cateId = $cate2Id;
        }

        DB::beginTransaction();
        try {

            $data = [
                'category_id' => $cateId,
                'title' => $goodCode,
                'picture' => $this->createImg($goodCode),
                'special' => $goodCode,
                'on_sale' => $saleStatus,
                'update_time' => time(),
            ];
            if ($id > 0) {
                $action = '编辑';
                //如果靓号是从下架改为上架状态，需要判断靓号是否已购买或在使用中
                $product = app('model_mall_products')->select('on_sale')->where('id', $id)->first();
                if ($product->on_sale == 2 && $saleStatus == 1) {
                    $orderId = app('model_mall_orders')
                        ->where('product_id', $id)
                        ->whereIn('state', [0, 1])
                        ->value('id');
                    if ($orderId) throw new BasicException(0, '正在使用中的靓号不能上架');
                }
                //更新
                app('model_mall_products')->where('id', $id)->update($data);
                //删除原始的商品价格信息
                app('model_mall_products_price')->where('product_id', $id)->delete();
            } else {
                $action = '添加';
                $data['add_time'] = time();
                $id = app('model_mall_products')->insertGetId($data);
            }

            //添加天数价格
            $daysPrices = json_decode($daysPrices, true);
            foreach ($daysPrices as $daysPrice) {
                if (empty($daysPrice['day']) || empty($daysPrice['price'])) throw new BasicException(0, '天数或价格不能为空');
                app('model_mall_products_price')->insert([
                    'product_id' => $id,
                    'day' => $daysPrice['day'],
                    'price' => $daysPrice['price'],
                    'original_price' => $daysPrice['price'],
                ]);
            }

            DB::commit();
            return Response::sendData([]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $e->getMessage());
        }
    }

    //获取靓号的一级和二级分类名称
    public function getCatesName($cateIds)
    {
        $cates = app('model_mall_categories')->select('id', 'parent_id', 'title')->whereIn('id', $cateIds)->get();

        $catesName = [];
        foreach ($cates as $cate) {
            if ($cate->parent_id == MallEnum::PRODUCT_CATE_ID_GOOD_CODE) {
                $catesName[$cate->id]['cate1_name'] = $cate->title;
                $catesName[$cate->id]['cate2_name'] = '';
            } else {
                $parentCateTitle = app('model_mall_categories')->where('id', $cate->parent_id)->value('title');
                $catesName[$cate->id]['cate1_name'] = $parentCateTitle;
                $catesName[$cate->id]['cate2_name'] = $cate->title;
            }
        }

        return $catesName;
    }

    //生成图片
    private function createImg($chars = 666)
    {
        $chars = (string)$chars;
        $charsLen = strlen($chars);

        $imgWidth = 108;
        $imgHeight = 108;

        //创建图片资源
        $im = imagecreate($imgWidth, $imgHeight);

        //设置并填充图片背景颜色
        $backgroundColor = imagecolorallocatealpha($im,49,53,126, 127); //透明度0-127,127表示完全透明
        imagefill($im,0, 0, $backgroundColor); //x=0，y=0代表从左上角开始填充

        //填充字符
        $charColor = imagecolorallocate($im,255,227,190);
        $charInterval = 8; //字符间隔
        $x = ($imgWidth - $charsLen * $charInterval) / 2;
        imagestring($im, 5, $x, 42, $chars, $charColor);

        //设置文件名和本地保存路径
        header('Content-type:image/png');
        $filename = time() . app('request')->admin_id . str_random(4) . '.png';
        $file = storage_path('app/') . $filename;
        imagepng($im, $file);

        $target = 'admin/pretty_number/' . $filename;
        $uploadRes = ObsService::putObs($target, $file);
        if ($uploadRes) {
            unlink($file); //删除压缩文件
            return env('OBS_HOST') .'/' . $target;
        } else {
            throw new BasicException(0, '自动生成靓号图片失败，请联系管理员');
        }
    }
}
